﻿// owner 蒋家伟

#include "TaskGroup.h"

// std
#include <ctime>

// jsdk
#include "Dbg_Warn_Define.h"
#include "ITaskDescription.h"
#include "TaskManager.h"
#include "TaskEventArgs.h"
#include "TaskEvent.h"

using namespace jsdk;

OwnerPtr<ITaskGroup> jsdk::TaskGroup::create(const std::wstring& description, std::vector<OwnerPtr<ITaskDescription>>&& opTaskDescriptions, uint32_t delayTime)
{
    return NEW_AS_OWNERPTR(TaskGroup, description, std::move(opTaskDescriptions), delayTime);
}

std::vector<OwnerPtr<ITask>> jsdk::TaskGroup::transformOwnShip()
{
    return std::move(m_tasks);
}

const ITaskDescription * jsdk::TaskGroup::getTaskDescription() const
{
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(false, L"任务组无法获取任务描述", L"蒋家伟", L"2023-07-31");
    return nullptr;
}

const TaskId& jsdk::TaskGroup::getGroupId() const
{
    return TaskId::s_InvalidTaskId;
}

bool jsdk::TaskGroup::isInGroup() const
{
    return false;
}

const TaskId & jsdk::TaskGroup::getTaskId() const
{
    return m_taskId;
}

void jsdk::TaskGroup::setTaskId(const TaskId& taskId)
{
    m_taskId = taskId;
    size_t value = taskId.toValue() * clock();
    for (auto& iter : m_tasks)
    {
        iter->setTaskId(TaskManager::getAvailableTaskId());
        iter->setTaskGroupId(m_taskId);
    }
}

void jsdk::TaskGroup::setTaskGroupId(const TaskId & taskGroupId)
{
    DBG_WARN_AND_RETURN_VOID_UNLESS(false, L"任务组无法设置任务组ID", L"蒋家伟", L"2023-07-31");
}

bool jsdk::TaskGroup::exctue()
{
    DBG_WARN_AND_RETURN_FALSE_UNLESS(false, L"任务组无法直接执行任务，请查看是任务组是否拆分出现错误", L"蒋家伟", L"2023-07-31");
    return false;
}

bool jsdk::TaskGroup::hasDelayTime() const
{
    return m_delayTime > 0;
}

void jsdk::TaskGroup::startTimer() const
{
    TaskId taskId = m_taskId;
    if (m_delayTime == 0)
    {
        DBG_WARN(L"此任务由于时间补偿导致了延迟为0, 实际延时大于等于原延迟", L"蒋家伟", L"2023-10-30");
        TaskEventArgs args(TaskEventType::DelayTaskTrigger, taskId);
        TaskEvent::get().sendEvent(&args);
    }
    else
    {
        QTimer::singleShot(m_delayTime, [taskId]() {
            TaskEventArgs args(TaskEventType::DelayTaskTrigger, taskId);
            TaskEvent::get().sendEvent(&args);
        });
    }
}

jsdk::TaskGroup::TaskGroup(const std::wstring& description, std::vector<OwnerPtr<ITaskDescription>>&& opTaskDescriptions, uint32_t delayTime) :
    m_description(description),
    m_delayTime(delayTime)
{
    for (auto& iter : opTaskDescriptions)
    {
        m_tasks.push_back(ITask::create(std::move(iter)));
    }

    DBG_WARN_UNLESS(delayTime < 20000, L"任务延迟时间不应该太长", L"蒋家伟", L"2023-08-17");
}
